import { create } from "zustand";
import type {
  FoodsListProps,
  CartListProps,
} from "@/pages/美团案例/types/Food/index";

import type { TakeawayStoreProps } from "@/store/types/takeaway";

const useTakeawayStore = create<TakeawayStoreProps>((set) => ({
  // 商品列表
  foodsList: [],
  setFoodsList: (foodsList: FoodsListProps[]) => set(() => ({ foodsList })),
  // 菜单激活下标值
  activeIndex: 0,
  setActiveIndex: (activeIndex: number) => set(() => ({ activeIndex })),
  // 购物车列表
  cartList: [],
  addCart: (cartList: CartListProps) =>
    set((state) => {
      const item = state.cartList.find((item) => item.id === cartList.id);
      if (item) {
        item.count++;
      } else {
        state.cartList.push({ ...cartList, count: 1 });
      }
      return { cartList: state.cartList };
    }),
  increCount: (id: number) =>
    set((state) => {
      const item = state.cartList.find((item) => item.id === id);
      if (item) {
        item.count++;
      }
      return { cartList: state.cartList };
    }),
  decreCount: (id: number) =>
    set((state) => {
      const item = state.cartList.find((item) => item.id === id);
      if (item) {
        item.count--;
        if (item.count <= 0) {
          state.cartList = state.cartList.filter((item) => item.id !== id);
        }
      }
      return { cartList: state.cartList };
    }),
  clearCart: () => set(() => ({ cartList: [] })),
}));

export { useTakeawayStore };
